package wjl.project.dubbotestshop;

import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

/**
 *
 * 为了便于实现MQ中的多播，重复消费等引入的概念。如果ConsumerA以及ConsumerB同在一个UserGroup，
 * 那么ConsumerA消费的数据ConsumerB就无法消费了。
 *
 * 即：所有usergroup中的consumer使用一套offset。
 * */

@Component
@Slf4j
public class KafkaReceiver {

    @Resource
    GoodsRepository goodsRepository;


    @KafkaListener(topics = {"goods"})
    public boolean listenBuyGoods(ConsumerRecord<String, String> record) {

        try {
            Optional<String> kafkaMessage = Optional.ofNullable(record.value());

            if (kafkaMessage.isPresent()) {

                Goods good = JSON.parseObject(kafkaMessage.get(),Goods.class);
                goodsRepository.updateGoodsNum(good.getGoodsNum(),good.getGoodsId());
                log.info("商品--》"+good.getGoodsId()+"---->成功写入数据库");
                return true;
            }else {
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
}